package xyz.wanwanwan.www.hrm.web.controller;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import xyz.wanwanwan.www.hrm.util.AjaxResult;
import xyz.wanwanwan.www.hrm.util.FastDfsUtil;

import java.io.IOException;
import java.util.Map;

@Controller
@RequestMapping("/fastdfs")
public class FastdfsController {
    @RequestMapping("/upload")
    @ResponseBody
    public AjaxResult upload(@RequestBody MultipartFile file){
        try {
            //原始文件名  b3.jpg
            String originalFilename = file.getOriginalFilename();
            //获取后缀名
            String extension = FilenameUtils.getExtension(originalFilename);
            //上传文件名 /group1/M00/00/02/dhma1l9aSjWAJydiAABfAC1c7rU963.jpg
            String uploadPath = FastDfsUtil.upload(file.getBytes(), extension);
            return AjaxResult.me().setResultObj(uploadPath).setMessage("上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("上传失败");
        }
    }
    @RequestMapping("/remove")
    @ResponseBody
    public AjaxResult remove(@RequestBody Map<String,Object> path){
        try {
            String originalPath = (String) path.get("path");
            //文件名  /group1/M00/00/03/dhma1l9aUjmAF51fAA5Kws9ji_k706.gif
            String substring = originalPath.substring(1);
            //获取组名
            String groupName = substring.substring(0, substring.indexOf("/"));
            //获取文件名
            String fileName = substring.substring(substring.indexOf("/") + 1);
            FastDfsUtil.delete(groupName,fileName);
            return AjaxResult.me().setMessage("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败");
        }
    }
}
